#
# mini_xml.py -- xml.dom.minidom wrapper for easy reading of xml files
# 
# author: Tom "Knio" Flanagan
#         knio@h4xn3t.net
#         theknio@gmail.com
#         irc.freenode.net - Knio - #python #pygame #py
#
# this file released under Public Domain
#


import os
from xml.dom import minidom

class Nxml:
    def __init__(self, dom):
        self.dom = dom
        self.attr = {}
        self.children = []
        self.namedChildren = {}
        self.value = ''

        self.getSelf()
        self.getChildren()

    def getSelf(self):
        self.name = self.dom.nodeName
        for i in self.dom.attributes.keys():
            value = self.dom.attributes[i].value
            if value.isdigit():
                value = int(value)
            else:
                try:    value = float(value)
                except: pass
            self.attr[str(i)] = value
        
    def getChildren(self):
        for i in self.dom.childNodes:
            if i.nodeType == 3: self.value += i.data
            if i.nodeType == 1:
                node = Nxml(i)
                self.children.append(node)
                self.namedChildren.setdefault(node.name, []).append(node)


    def __getattr__(self, attr):
        try:    return self.namedChildren[attr]
        except KeyError: raise AttributeError

    def __getitem__(self, item):
        return self.attr[item]
        

def parse(what):
    if (what.__class__ is file) or os.access(what, os.R_OK):        
        return Nxml(minidom.parse(what).firstChild)
    else:
        return Nxml(minidom.parseString(what).firstChild)


    
